package com.itheima.ithmshortlink.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.ithmshortlink.mapper.ShortLinkMapper;
import com.itheima.ithmshortlink.dto.LongLink;
import com.itheima.ithmshortlink.pojos.UrlMapping1;
import com.itheima.ithmshortlink.service.ShortLinkService;
import com.itheima.ithmshortlink.utils.NumberUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Slf4j
public class ShortLinkServiceImpl extends ServiceImpl<ShortLinkMapper,UrlMapping1> implements ShortLinkService {




    @Value("${server.port}")
    private String port;

    /**
     * @description: 将前段传递过来的长链转换成短链响应给前端
     * @author: 龙宇
     * @date: 2021/7/3 : 21:07
     * @params: null:
     * @return: null
     */
    @Override
    public String toShortLink(LongLink longLink) {

        //健壮性判断
        if (longLink==null||
                StringUtils.isBlank(longLink.getName()) ||
                StringUtils.isBlank(longLink.getDescription())||
                StringUtils.isBlank(longLink.getUrl())){
            return "信息不全,请将所有信息填写完成再提交";
        }
        log.info("前端传递的数据: "+longLink);
        //创建表对应的实体类对象
        UrlMapping1 urlMapping1 = new UrlMapping1();

        //封装数据
        urlMapping1.setUrl(longLink.getUrl());

        log.info("封装的实体类对象数据: "+urlMapping1);

        //添加数据
        boolean flag = save(urlMapping1);

        log.info("添加数据结果: "+flag);
        //判断是否添加成功
        if (!flag){

            //添加失败,提示QIANDUAN
            return "添加失败,请稍后再试";
        }

        //添加成功  判断id  将id  转换成64进制返回给前端
        Long id = urlMapping1.getId();

        //转换成
        long shortId = (id - 1) * 1000 + 1;

        String shortUrl = NumberUtils.decimal2base62(shortId);

        //拼接短链
        String shortLink =  "http://localhost:"+port+"/"+ shortUrl;

        //返回给前端
        return shortLink;
    }




    /**
     * @description:
     * @author: 龙宇
     * @date: 2021/7/4 : 0:33
     * @params: null:
     * @return: null
     */
    @Override
    public void updateShortLinkStats(String shortUrl, Integer status) {

    }
}
